<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/12/6
 * Time: 9:21
 */

namespace App\Extend\SysExtend\File;

use App\Extend\SysExtend\Helper;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config;

/**
 * 文件上传类
 * Class FileManager
 * @package App\Extend\SysExtend\File
 */
class FileManager
{
    use Singleton;

    /**
     * @var string 驱动类
     */
    private $driver;

    /**
     * @var mixed 配置项
     */
    private $config;

    /**
     * FileManager constructor.
     * @param string $driver
     * @throws \Throwable
     */
    private function __construct(string $driver = '')
    {
        $driver = $driver ? $driver : Helper::config('file.driver');
        $this->config = Helper::config('file.'.$driver);
        $this->driver = new $driver($this->config);
    }

    /**
     * 文件上传
     * @param string|array $file_info 文件信息
     * @param string $type 文件上传方式
     * @param string $path 保存路径
     * @return string 路径
     */
    public function upload($file_info, $type = 'file',$path = '')
    {
        if($type == 'file') {
            return $this->driver->uploadBin($file_info, $path);
        }
        return $this->driver->uploadBase64($file_info, $path);
    }

    /**
     * 获取文件网络路径
     * @param string $path 本地路径
     * @return string 网络路径
     */
    public function get(string $path)
    {
        return $this->driver->get($path);
    }


    /**
     * 将网络路径转为服务器路径
     * @param string $url
     * @return string
     * @throws \Throwable
     */
    public function net2Path(string $url)
    {
        $server = Config::getInstance()->getConf('WEB_URL') . '/' . (Helper::config('extend.resource_dir') ?? '');
        return ltrim(str_replace($server,'',$url),'/');
    }

    /**
     * 删除文件
     * @param string $path 路径
     * @return mixed
     */
    public function del(string $path)
    {
        return $this->driver->delete($path);
    }
}